#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <iot_pwm.h>
#include "iot_i2c.h"
#include <memory.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "ssd1306_oled.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_errno.h"
#include "iot_adc.h"
#include "hi_time.h"
#include "app_demo_i2c_oled.h"
#include "Sensor.h"
//微信小程序
#include <hi_task.h>
#include <hi_wifi_api.h>
#include <hi_mux.h>
#include <hi_io.h>
#include <hi_gpio.h>
#include "iot_config.h"
#include "iot_log.h"
#include "iot_main.h"
#include "iot_profile.h"
//串口
#include <hi_stdlib.h>
#include "hisignalling_protocol.h"
#include <hi_uart.h>
#include "app_demo_uart.h"
#include <iot_uart.h>

#define TASK_STAK_SIZE    (1024*10)
#define AHT20_BAUDRATE (400 * 1000)
/* attribute initiative to report */
#define TAKE_THE_INITIATIVE_TO_REPORT

/* oc request id */
#define CN_COMMADN_INDEX                    "commands/request_id="

unsigned char drink_count=0,smoke_count=0,phone_count=0,Invalid_count=0;
int g_ligthStatus = -1;
UartDefConfig uartDefConfig = {0};

//串口
static void Uart1GpioCOnfig(void)
{
#ifdef ROBOT_BOARD
    IoSetFunc(HI_IO_NAME_GPIO_5, IOT_IO_FUNC_GPIO_5_UART1_RXD);
    IoSetFunc(HI_IO_NAME_GPIO_6, IOT_IO_FUNC_GPIO_6_UART1_TXD);
    /* IOT_BOARD */
#elif defined (EXPANSION_BOARD)
    IoSetFunc(HI_IO_NAME_GPIO_0, IOT_IO_FUNC_GPIO_0_UART1_TXD);
    IoSetFunc(HI_IO_NAME_GPIO_1, IOT_IO_FUNC_GPIO_1_UART1_RXD);
#endif
}
int SetUartRecvFlag(UartRecvDef def)
{
    if (def == UART_RECV_TRUE) {
        uartDefConfig.g_uartReceiveFlag = HI_TRUE;
    } else {
        uartDefConfig.g_uartReceiveFlag = HI_FALSE;
    }
    
    return uartDefConfig.g_uartReceiveFlag;
}

int GetUartConfig(UartDefType type)
{
    int receive = 0;

    switch (type) {
        case UART_RECEIVE_FLAG:
            receive = uartDefConfig.g_uartReceiveFlag;
            break;
        case UART_RECVIVE_LEN:
            receive = uartDefConfig.g_uartLen;
            break;
        default:
            break;
    }
    return receive;
}
void ResetUartReceiveMsg(void)
{
    (void)memset_s(uartDefConfig.g_receiveUartBuff, sizeof(uartDefConfig.g_receiveUartBuff),
        0x0, sizeof(uartDefConfig.g_receiveUartBuff));
}

unsigned char *GetUartReceiveMsg(void)
{
    return uartDefConfig.g_receiveUartBuff;
}


//微信小程序
typedef void (*FnMsgCallBack)(hi_gpio_value val);

typedef struct FunctionCallback {
    hi_bool  stop;
    hi_u32 conLost;
    hi_u32 queueID;
    hi_u32 iotTaskID;
    FnMsgCallBack    msgCallBack;
}FunctionCallback;
FunctionCallback g_functinoCallback;

static void DeviceConfigInit(hi_gpio_value val)
{
    hi_io_set_func(HI_IO_NAME_GPIO_9, HI_IO_FUNC_GPIO_9_GPIO);
    hi_gpio_set_dir(HI_GPIO_IDX_9, HI_GPIO_DIR_OUT);
    hi_gpio_set_ouput_val(HI_GPIO_IDX_9, val);
}

static int  DeviceMsgCallback(FnMsgCallBack msgCallBack)
{
    g_functinoCallback.msgCallBack = msgCallBack;
    return 0;
}

static void wechatControlDeviceMsg(hi_gpio_value val)
{
    DeviceConfigInit(val);
}


//串口通信
static hi_void *UartDemoTask(char *param)
{
    hi_u8 uartBuff[UART_BUFF_SIZE] = {0};
   
    hi_unref_param(param);
    printf("Initialize uart demo successfully, please enter some datas via DEMO_UART_NUM port...\n");
    Uart1GpioCOnfig();
    for (;;) {
        //555 
        uartDefConfig.g_uartLen = IoTUartRead(DEMO_UART_NUM, uartBuff, UART_BUFF_SIZE);
        if(uartBuff[5]==2)//drink
        {
            drink_count = uartBuff[3];
        }

        if(uartBuff[5]==3)//phone
        {
            phone_count = uartBuff[3];
        }

        if(uartBuff[5]==4)//smoke
        {
            smoke_count = uartBuff[3];
        }

        if ((uartDefConfig.g_uartLen > 0) && (uartBuff[0] == 0xaa) && (uartBuff[1] == 0x55)) {
            if (GetUartConfig(UART_RECEIVE_FLAG) == HI_FALSE) {
                (void)memcpy_s(uartDefConfig.g_receiveUartBuff, uartDefConfig.g_uartLen,
                    uartBuff, uartDefConfig.g_uartLen);
                (void)SetUartRecvFlag(UART_RECV_TRUE);
            }
        }
        TaskMsleep(1000); /* 20:sleep 20ms (改为1s)*/
    }
    return HI_NULL;
}
/* publish sample */
hi_void IotPublishSample(void)
{
    IoTGpioInit(IOT_IO_NAME_GPIO_13);
    IoSetFunc(IOT_IO_NAME_GPIO_13, IOT_IO_FUNC_GPIO_13_I2C0_SDA);
    IoTGpioInit(IOT_IO_NAME_GPIO_14);
    IoSetFunc(IOT_IO_NAME_GPIO_14, IOT_IO_FUNC_GPIO_14_I2C0_SCL);
    OledInit();
    OledFillScreen(0);
    IoTI2cInit(0, AHT20_BAUDRATE);

    unsigned int ret=0,qut=0;
    unsigned short MQ3 = 0;unsigned char MQ3_flag=0;unsigned char MQ3_str[10]={0};
    ret = AdcRead(IOT_ADC_CHANNEL_5, &MQ3,IOT_ADC_EQU_MODEL_4, IOT_ADC_CUR_BAIS_DEFAULT, 0xff);
    unsigned short fsr = 0;unsigned char fsr_flag=0;unsigned char FSR_str[10]={0};
    qut = AdcRead(IOT_ADC_CHANNEL_0, &fsr, IOT_ADC_EQU_MODEL_4, IOT_ADC_CUR_BAIS_DEFAULT,  0xF0);
    float val_mq3 = MQ3;
    float val_fsr = fsr;
    unsigned char heart_count[5] ={92,93,95,91,98},i=0;

    FlaotToString(val_mq3, MQ3_str);
    OledShowStr(1, 1, "MQ3:", 1);
    OledShowStr(40, 1, MQ3_str, 1);
    
    (MQ3 >=800) ? (MQ3_flag=1): (MQ3_flag=0) ;
    if(MQ3_flag ==1)
    {
       OledShowStr(1, 3, "You are drank!", 1);
    }

   FlaotToString(val_fsr,FSR_str);
    OledShowStr(1, 5,"FSR:", 1);
    OledShowStr(40, 5,FSR_str, 1);
    
    (fsr >=800)? (fsr_flag=1) : (fsr_flag=0);
    if(fsr_flag ==1)
    {
        OledShowStr(1, 7,"Drive properly!", 1);
    }
    /* reported attribute */
    WeChatProfile weChatProfile = {
        .subscribeType = "type",
        .status.subState = "state",
        .status.subReport = "reported",
        .status.reportVersion = "version",
        .status.Token = "clientToken",
        /* report motor */
        .reportAction.subDeviceActionheart = "heart",
        .reportAction.heartActionStatus = heart_count[i], /* 0 : motor off */
        /* report MQ3 */
        .reportAction.subDeviceActionMQ3 = "MQ3",
        .reportAction.MQ3ActionData = MQ3, /* 30 :MQ3 data */
        /* report FSR */
        .reportAction.subDeviceActionFSR = "FSR",
        .reportAction.FSRActionData = fsr, /* FSR data */
        //3516串口通信数据
        .reportAction.subDeviceActiondrink = "drink",
        .reportAction.drinkActionData =  drink_count,
        .reportAction.subDeviceActionphone = "phone",
        .reportAction.phoneActionData =  phone_count,
        .reportAction.subDeviceActionsmoke = "smoke",
        .reportAction.smokeActionData =  smoke_count,
       
      };  
      i++;
       if(i ==5) i=0;
    /* profile report */
    IoTProfilePropertyReport(CONFIG_USER_ID, &weChatProfile);
}
static hi_void *DemoEntry(const char *arg)
{
    WifiStaReadyWait();
    cJsonInit();
    IoTMain();
    /* 主动上报 */
#ifdef TAKE_THE_INITIATIVE_TO_REPORT
    while (1) {
        /* 用户可以在这调用发布函数进行发布，需要用户自己写调用函数 */
        IotPublishSample(); // 发布例程
#endif
       hi_sleep(5000);
    }
    return NULL;
}

void SensorTask(void* parame)
{
    (void)parame;
    printf("start test Sensor\r\n");
    unsigned int time = 5000;
    while (1) 
    {
       hi_sleep(time);
    }
}


static void SensorDemo(void)
{
     osThreadAttr_t attr;
    IoTWatchDogDisable();

    //串口
    hi_u32 ret = 0;
    IotUartAttribute uartAttr = {
        .baudRate = 115200, /* baudRate: 115200 */
        .dataBits = 8, /* dataBits: 8bits */
        .stopBits = 1, /* stop bit */
        .parity = 0,
    };
    /* Initialize uart driver */
    ret = IoTUartInit(DEMO_UART_NUM, &uartAttr);
    if (ret != HI_ERR_SUCCESS) {
        printf("Failed to init uart! Err code = %d\n", ret);
        return;
    }

    attr.name = "SensorTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = TASK_STAK_SIZE;
    attr.priority = osPriorityNormal;
    
    if (osThreadNew((osThreadFunc_t)DemoEntry, NULL, &attr) == NULL) 
    {
        printf("[mqtt] Falied to create IOTDEMO!\n");
    }


    if (osThreadNew(SensorTask, NULL, &attr) == NULL) 
    {
        printf("[SensorDemo] Falied to create SensorTask!\n");
    }

    if (osThreadNew((osThreadFunc_t)UartDemoTask, NULL, &attr) == NULL)
    {
        printf("Falied to create uart demo task!\n");
    }

}

SYS_RUN(SensorDemo);

